package com.fount4j.generator.introspector.extend;

import com.fount4j.generator.context.GeneratorContext;
import com.fount4j.generator.exception.GenerateException;
import com.fount4j.generator.info.MapperInfo;
import com.fount4j.generator.introspector.FileIntrospector;
import com.fount4j.generator.util.GeneratorFileUtils;
import com.fount4j.generator.util.StringUtils;

import java.io.File;
import java.io.IOException;

/**
 * MyBatis 映射文件解析器
 *
 * @author Morven 2017/1/5
 */
public class MyBatisMapperIntrospector extends FileIntrospector {
    /** Mapper 文件名相对于实体类的后缀 */
    protected String nameSuffix = "Mapper";

    @Override
    public void introspect(GeneratorContext context) {
        MapperInfo mapperInfo = new MapperInfo();
        introspectName(context, mapperInfo);
        introspectFile(context, mapperInfo);
        context.putInfo(infoKey, mapperInfo);
    }

    /**
     * 解析文件路径
     *
     * @param context 生成器上下文
     */
    private void introspectFile(GeneratorContext context, MapperInfo info) {
        String packageName = context.getTableConfig().getString("mapperPackage");
        if (StringUtils.isBlank(packageName)) {
            packageName = super.packageName;
        }
        File file = GeneratorFileUtils.getFile(super.resourcePath, packageName, info.getName() + ".xml");
        info.setFile(file);
        try {
            info.setCustomContent(GeneratorFileUtils.getCustomContent(file));
        } catch (IOException e) {
            throw new GenerateException("读取文件自定义内容出错: " + file, e);
        }
    }

    /**
     * 解析文件名
     *
     * @param context 生成器上下文
     */
    protected void introspectName(GeneratorContext context, MapperInfo info) {
        String mapperName = context.getTableConfig().getString("mapperName");
        if (StringUtils.isBlank(mapperName)) {
            mapperName = context.getInfo("entity").getName() + this.nameSuffix;
        }
        info.setName(mapperName);
    }

    public String getNameSuffix() {
        return nameSuffix;
    }

    public void setNameSuffix(String nameSuffix) {
        this.nameSuffix = nameSuffix;
    }
}
